<?php

namespace app\subscribe\bill;


use think\Event;
use think\facade\Db;
use app\common\repositories\bill\BillCateRepository;
use app\common\repositories\bill\BillLogRepository;
use app\common\repositories\bill\BillBasicRepository;
use app\common\repositories\bill\BillFinanceRepository;
use app\common\repositories\bill\BillCatalogRepository;
use app\common\repositories\items\users\ItemsUsersLogRepository;

class BillSubscribe
{

    /**
     * 监听账单创建
     * @param $data
     */
    public function onCreateBill($data)
    {
        $billInfo = $data['billInfo'];
        $userId = $data['userId'] ?? 0;

        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);

        $remark = $billInfo['number'] . ' 账单创建';
        $billLogRepository->addInfo($billInfo['id'], $userId, $remark);

        /** @var ItemsUsersLogRepository $repository */
        $repository = app()->make(ItemsUsersLogRepository::class);
        $repository->addInfo($billInfo['items_id'], $userId, 'BILL.BASIC.ADD', $billInfo, $remark);
    }


    /**
     * 监听账单编辑
     * @param $data
     */
    public function onUpdateBill($data)
    {
        $billInfo = $data['billInfo'];
        $userId = $data['userId'] ?? 0;
        $msg = $data['remark'] ?? '';

        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);

        $remark = $billInfo['number'] . ' 账单编辑 ' . $msg;
        $billLogRepository->addInfo($billInfo['id'], $userId, $remark);

        /** @var ItemsUsersLogRepository $repository */
        $repository = app()->make(ItemsUsersLogRepository::class);
        $repository->addInfo($billInfo['items_id'], $userId, 'BILL.BASIC.EDIT', $data);
    }


    /**
     * 监听账单审核
     *
     * @param $data
     */
    public function onAuditBill($data)
    {
        $billInfo = $data['billInfo'];
        $userId = $data['userId'] ?? 0;

        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);

        $remark = $billInfo['number'] . ' 账单审核';
        $billLogRepository->addInfo($billInfo['id'], $userId, $remark);

        /** @var BillCatalogRepository $billCatalogRepository */
        $billCatalogRepository = app()->make(BillCatalogRepository::class);
        $billCatalogRepository->updateByBillId($billInfo['id'], 2);

        /** @var ItemsUsersLogRepository $repository */
        $repository = app()->make(ItemsUsersLogRepository::class);
        $repository->addInfo($billInfo['items_id'], $userId, 'BILL.BASIC.AUDIT', $billInfo, $remark);

        # 账单审核成功发送通知
        \app\jobs\Queue::push(\app\jobs\SendMessageJob::class, [
            'message_type' => 'bill_create',
            'items_id' => $billInfo['items_id'],
            'params' => [
                'bill_id' => $billInfo['id']
            ]
        ]);
    }


    /**
     * 监听账单作废
     *
     * @param $data
     */
    public function onInvalidBill($data)
    {
        $billInfo = $data['billInfo'];
        $userId = $data['userId'] ?? 0;
        $note = $data['remark'] ?? '';

        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);

        $remark = $billInfo['number'] . ' 账单作废' . $note;
        $billLogRepository->addInfo($billInfo['id'], $userId, $remark);

        ## 账单明细作废
        /** @var BillCatalogRepository $billCatalogRepository */
        $billCatalogRepository = app()->make(BillCatalogRepository::class);

        $billCatalogRepository->getSearch([])
            ->where('bill_id', $billInfo['id'])
            ->whereIn('status', [1, 2, 5, 8])
            ->update(['status' => 4]);

        /** @var ItemsUsersLogRepository $repository */
        $repository = app()->make(ItemsUsersLogRepository::class);
        $repository->addInfo($billInfo['items_id'], $userId, 'BILL.BASIC.INVALID', $billInfo, $remark);
    }


    /**
     * 监听账单明细作废
     *
     * @param $data
     */
    public function oninvalidCatalog($data)
    {
        $catalogInfo = $data['catalogInfo'];
        $userId = $data['userId'] ?? 0;
        $invalidRemark = $data['invalidRemark'] ?? '';

        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);

        $remark = $invalidRemark . ' 账单作废';
        $billLogRepository->addInfo($catalogInfo['bill_id'], $userId, $remark, $catalogInfo['id']);

        /** @var ItemsUsersLogRepository $repository */
        $repository = app()->make(ItemsUsersLogRepository::class);
        $repository->addInfo($catalogInfo['items_id'], $userId, 'BILL.BASIC.CATALOG.INVALID', $catalogInfo, $remark);
    }


    /**
     * 监听账单延期
     * @param $data
     */
    public function onPostponeBill($data)
    {
        $billInfo = $data['billInfo'];
        $userId = $data['userId'] ?? 0;
        $day = $data['day'] ?? 0;
        $cutoffDate = $data['cutoff_date'];
        # 此账单之前是否有逾期
        if ($billInfo['overdue_day'] > 0 && $cutoffDate >= date('Y-m-d')) {
            # 延期账单 通电

        }

        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);
        $remark = $billInfo['number'] . ' 账单延期 ' . $day . '天，最晚支付日至 ' . $cutoffDate;
        $billLogRepository->addInfo($billInfo['id'], $userId, $remark);

        /** @var ItemsUsersLogRepository $repository */
        $repository = app()->make(ItemsUsersLogRepository::class);
        $repository->addInfo($billInfo['items_id'], $userId, 'BILL.BASIC.POSTPONE', $billInfo, $remark);
    }

    /**
     * 监听账单支付成功
     * @param $data
     */
    public function onPaySuccessBill($data)
    {
        $billInfo = $data['billInfo'];
        $payType = $data['payType'];
        $payAmount = $data['payAmount'];
        $payMethod = $data['payMethod'];
        $status = $data['status'] ?? 0;
        $userId = $data['userId'] ?? 0;

        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);
        if ($payType == 1) {
            if ($status == 9) {
                $remark = '线上支付成功 ' . $payAmount . '元';
            } else {
                $remark = '线上支付 ' . $payAmount . '元';
            }
        } else {
            $remark = '线下支付' . $payAmount . ' 元';
        }
        $billLogRepository->addInfo($billInfo['id'], $userId, $remark);

        ## 添加宿舍流水明细
        /** @var BillFinanceRepository $billFinanceRepository */
        $billFinanceRepository = app()->make(BillFinanceRepository::class);

        ## 其它费用
        $insertData = [];
        /** @var BillCatalogRepository $billCatalogRepository */
        $billCatalogRepository = app()->make(BillCatalogRepository::class);
        $catalogList = $billCatalogRepository->getSearch([])
            ->where('status', 'in', '2,5,8')
            ->where('bill_id', $billInfo['id'])
            ->select();
        foreach ($catalogList as $k => $v) {
            $insertData[] = [
                'pay_type' => $payType,
                'pay_method' => $payMethod,
                'cate_id' => $v['cate_id'],
                'is_type' => $v['is_type'],
                'amount' => $v['amount'],
                'start_date' => $v['start_date'],
                'end_date' => $v['end_date'],
                'user_id' => $billInfo['user_id'],
                'bill_id' => $billInfo['id'],
                'room_id' => $billInfo['room_id'],
                'month_time' => $billInfo['month_time'],
                'property_id' => $billInfo['property_id'],
                'contract_id' => $billInfo['contract_id'] ?? '',
                'items_id' => $billInfo['items_id'],
                'finance_no' => $billFinanceRepository->getFinanceNo($v['property_id']),
            ];
        }
        $billFinanceRepository->insertAll($insertData);
        ## 更新账单明细状态
        $billCatalogRepository->updateByBillId($billInfo['id'], 9);

        ## 账单支付成功发送通知
        \app\jobs\Queue::push(\app\jobs\SendMessageJob::class, [
            'message_type' => 'bill_pay_success',
            'items_id' => $billInfo['items_id'],
            'params' => [
                'pay_type' => $data['payType'],
                'pay_method' => $payMethod,
                'bill_id' => $billInfo['id'],
                'pay_amount' => $payAmount
            ]
        ]);

    }


    /**
     * 监听账单明细支付成功
     * @param $data
     */
    public function onPayCatalogSuccessBill($data)
    {
        $catalogInfo = $data['catalogInfo'];
        $payType = $data['payType'];
        $payAmount = $data['payAmount'];
        $payMethod = $data['payMethod'];
        $status = $data['status'] ?? 0;
        $userId = $data['userId'] ?? 0;

        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);
        if ($payType == 1) {
            if ($status == 9) {
                $remark = '线上支付成功 ' . $payAmount . '元';
            } else {
                $remark = '线上支付 ' . $payAmount . '元';
            }
        } else {
            $remark = '线下支付' . $payAmount . ' 元';
        }
        $billLogRepository->addInfo($catalogInfo['bill_id'], $userId, $remark, $catalogInfo['id']);

        ## 添加支付流水明细
        /** @var BillFinanceRepository $billFinanceRepository */
        $billFinanceRepository = app()->make(BillFinanceRepository::class);
        $insertData = [
            'amount' => $payAmount,
            'pay_type' => $payType,
            'pay_method' => $payMethod,
            'catalog_id' => $catalogInfo['id'],
            'bill_id' => $catalogInfo['bill_id'],
            'room_id' => $catalogInfo['room_id'],
            'cate_id' => $catalogInfo['cate_id'],
            'is_type' => $catalogInfo['is_type'],
            'user_id' => $catalogInfo['user_id'],
            'end_date' => $catalogInfo['end_date'],
            'month_time' => $catalogInfo['month_time'],
            'items_id' => $catalogInfo['items_id'],
            'start_date' => $catalogInfo['start_date'],
            'property_id' => $catalogInfo['property_id'],
            'contract_id' => $catalogInfo['contract_id'] ?? '0',
            'finance_no' => $billFinanceRepository->getFinanceNo($catalogInfo['property_id']),
        ];
        $billFinanceRepository->create($insertData);

        ## 检测账单支付状态
        /** @var BillBasicRepository $BillBasicRepository */
        $BillBasicRepository = app()->make(BillBasicRepository::class);
        $BillBasicRepository->monitorBillPayStatus($catalogInfo['bill_id']);
    }

    /**
     * 监听账单确认收款
     * @param $data
     */
    public function onConfirmPayBill($data)
    {
        $courseInfo = $data['courseInfo'];
        $userId = $data['userId'] ?? 0;
        $amount = $data['amount'];

        /** @var BillBasicRepository $BillBasicRepository */
        $BillBasicRepository = app()->make(BillBasicRepository::class);
        $updateData = [];
        if ($courseInfo['pay_type'] == 1) {
            $updateData['online_amount'] = Db::raw('`online_amount`+' . $amount);
        } elseif ($courseInfo['pay_type'] == 2) {
            $updateData['offline_amount'] = Db::raw('`offline_amount`+' . $amount);
        }
        $BillBasicRepository->update($courseInfo['bill_id'], $updateData);
        $billInfo = $BillBasicRepository->get($courseInfo['bill_id']);

        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);
        ## 添加账单确认收款日志
        $remark = ($billInfo['number'] ?? '') . ' 收款确认 ' . $amount;
        $billLogRepository->addInfo($billInfo['id'], $userId, $remark);

        if ($billInfo['check_amount'] >= $billInfo['real_Amount']) {
            ## 账单支付完成事件
            $BillBasicRepository->update($courseInfo['bill_id'], ['status' => 9]);

            ## 添加宿舍流水明细
            /** @var BillFinanceRepository $billFinanceRepository */
            $billFinanceRepository = app()->make(BillFinanceRepository::class);

            ## 其它费用
            $insertData = [];
            /** @var BillCatalogRepository $billCatalogRepository */
            $billCatalogRepository = app()->make(BillCatalogRepository::class);
            $catalogList = $billCatalogRepository->getSearch([])
                ->where('bill_id', $billInfo['id'])->select();
            foreach ($catalogList as $k => $v) {
                $insertData[] = [
                    'cate_id' => $v['cate_id'],
                    'is_type' => $v['is_type'],
                    'amount' => $v['amount'],
                    'start_date' => $v['start_date'],
                    'end_date' => $v['end_date'],
                    'finance_no' => $billInfo['number'],
                    'user_id' => $billInfo['user_id'],
                    'bill_id' => $billInfo['id'],
                    'room_id' => $billInfo['room_id'],
                    'property_id' => $billInfo['property_id'],
                    'contract_id' => $billInfo['contract_id'],
                    'items_id' => $billInfo['items_id'],
                ];
            }

            $billFinanceRepository->insertAll($insertData);

        }
    }


    /**
     * 监听账单删除
     * @param $data
     */
    public function onDeleteBill($data)
    {
        $billInfo = $data['billInfo'];
        $remark = $data['remark'] ?? '';
        $userId = $data['userId'] ?? 0;

        ## 删除账单明细
        /** @var BillCatalogRepository $billCatalogRepository */
        $billCatalogRepository = app()->make(BillCatalogRepository::class);
        $billCatalogRepository->deleteByBillId($billInfo['id']);

        ## 删除账单日志
        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);
        $billLogRepository->deleteByBillId($billInfo['id']);

        ##  删除账单信息
        /** @var BillBasicRepository $BillBasicRepository */
        $BillBasicRepository = app()->make(BillBasicRepository::class);
        $BillBasicRepository->deleteByBillId($billInfo['id']);

        /** @var ItemsUsersLogRepository $repository */
        $repository = app()->make(ItemsUsersLogRepository::class);
        $remark = $billInfo['number'] . ' 账单删除 ' . $remark;
        $repository->addInfo($billInfo['items_id'], $userId, 'BILL.BASIC.DEL', $billInfo, $remark);
    }

    /**
     * 监听账单删除
     * @param $data
     */
    public function onDeleteBillCatalog($data)
    {
        $billCatalogInfo = $data['billCatalogInfo'];
        $userId = $data['userId'] ?? 0;

        /** @var BillCateRepository $cateRepository */
        $cateRepository = app()->make(BillCateRepository::class);
        $cateInfo = $cateRepository->get($billCatalogInfo['cate_id']);
        $cataName = $cateInfo['cate_name'] ?? '';
        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);
        $remark = ' 删除账单明细  ' . $cataName . ' ' . $billCatalogInfo['total_amount'];
        $billLogRepository->addInfo($billCatalogInfo['bill_id'], $userId, $remark);

        /** @var ItemsUsersLogRepository $repository */
        $repository = app()->make(ItemsUsersLogRepository::class);
        $repository->addInfo($billCatalogInfo['items_id'], $userId, 'BILL.CATALOG.DEL', $billCatalogInfo);
    }


    /**
     * 监听账单催收
     * @param $data
     * @return void
     *
     * @author Amos
     * 2024-06-17 19:22
     */
    public function onBillPayUrge($data)
    {
        $billInfo = $data['billInfo'];
        $userId = $data['userId'] ?? 0;

        /** @var BillLogRepository $billLogRepository */
        $billLogRepository = app()->make(BillLogRepository::class);

        $remark = $billInfo['month_time'] . ' 月账单编号: ' . $billInfo['number'] . ' 账单崔缴';
        $billLogRepository->addInfo($billInfo['id'], $userId, $remark);

        ## 账单催收发送通知
        \app\jobs\Queue::push(\app\jobs\SendMessageJob::class, [
            'message_type' => 'bill_urge',
            'items_id' => $billInfo['items_id'],
            'params' => [
                'bill_id' => $billInfo['id']
            ]
        ]);
    }


    public function subscribe(Event $event)
    {
        $event->listen('bill.create', [$this, 'onCreateBill']);## 创建账单
        $event->listen('bill.approval', [$this, 'onAuditBill']);## 审核账单
        $event->listen('bill.invalid', [$this, 'onInvalidBill']);## 作废账单
        $event->listen('bill.invalidCatalog', [$this, 'oninvalidCatalog']);## 作废账单明细
        $event->listen('bill.postpone', [$this, 'onPostponeBill']);## 账单延期
        $event->listen('bill.paySuccess', [$this, 'onPaySuccessBill']);## 账单支付
        $event->listen('bill.payUrge', [$this, 'onBillPayUrge']);## 账单催收
        $event->listen('bill.payCatalogSuccess', [$this, 'onPayCatalogSuccessBill']);## 账单明细支付
        $event->listen('bill.confirmPay', [$this, 'onConfirmPayBill']);## 账单确认收款
        $event->listen('bill.delete', [$this, 'onDeleteBill']);## 账单删除
        $event->listen('bill.catalog.delete', [$this, 'onDeleteBillCatalog']);## 账单明细删除
    }
}